package com.tigerlee.stopmusic;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.view.KeyEvent;

public class MediaPlaybackReceiver extends BroadcastReceiver{
	
	public static final String PLAY_ACTION = "com.tigerlee.stopmusic.play";
	public static final String TOGGLEPAUSE_ACTION = "com.tigerlee.stopmusic.toggle";
	public static final String PAUSE_ACTION = "com.tigerlee.stopmusic.pause";
	public static final String STOP_ACTION = "com.tigerlee.stopmusic.stop";
	public static final String PREVIOUS_ACTION = "com.tigerlee.stopmusic.previous";
	public static final String NEXT_ACTION = "com.tigerlee.stopmusic.next";
	private static final String TAG = "MediaPlaybackReceiver";
	
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		if(intent == null) return;
		int keycode = KeyEvent.KEYCODE_MEDIA_STOP;
		if (TOGGLEPAUSE_ACTION.equals(intent.getAction())) {
			keycode = KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE;
		}else if(NEXT_ACTION.equals(intent.getAction())){
			keycode = KeyEvent.KEYCODE_MEDIA_NEXT;
		}else if(PREVIOUS_ACTION.equals(intent.getAction())){
			keycode = KeyEvent.KEYCODE_MEDIA_PREVIOUS;
		}
		long eventtime = SystemClock.uptimeMillis();
		Intent downIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
		KeyEvent downEvent = new KeyEvent(eventtime, eventtime,
				KeyEvent.ACTION_DOWN, keycode, 0);
		downIntent.putExtra(Intent.EXTRA_KEY_EVENT, downEvent);
		context.sendOrderedBroadcast(downIntent, null);
		
		Intent upIntent = new Intent(Intent.ACTION_MEDIA_BUTTON, null);
		KeyEvent upEvent = new KeyEvent(eventtime, eventtime,
				KeyEvent.ACTION_UP, keycode, 0);
		upIntent.putExtra(Intent.EXTRA_KEY_EVENT, upEvent);
		context.sendOrderedBroadcast(upIntent, null);
	}

}
